package com.bridgetree.jubaocrm.ui.project;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.bridgetree.jubaocrm.R;
import com.bridgetree.jubaocrm.model.CRMUserBaseInfo;
import com.bridgetree.jubaocrm.service.JsonObjectPostRequest;
import com.bridgetree.jubaocrm.service.Network;
import com.bridgetree.jubaocrm.ui.Contents;
import com.bridgetree.jubaocrm.ui.LoginUtil;
import com.bridgetree.jubaocrm.ui.ProgressDialogUtil;
import com.bridgetree.jubaocrm.util.LoginError;
import com.bridgetree.jubaocrm.util.Projects;

public class XMChildActivity extends Activity {
	private Context mContext;
	private final String TAG = "XMChildActivity";
	private ListView xm_12_lv = null;
	private XMChildAdapter mXMChildAdapter = null;
	private ArrayList<String> proInfoListData = null;
	private Projects mProjects ;
	static int index = 1;
	private String user_id =""; 
	private String token ="";
	
	private boolean isFoujue=false;
	private RelativeLayout xm_project_add_RelativeLayout;
	public static final int foujue=10001;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.xm_12);
		mContext=this;

		Intent intent = getIntent();
		if (intent == null) {
			Log.e(TAG, "intent is null");
			return;
		}

		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
		user_id = prefs.getString(Contents.KEY_PERSONAL_LOGIN_USEID, ""); 
		token = prefs.getString(Contents.KEY_PERSONAL_LOGIN_TAKEN, "");
		
		TextView xm_12_tv_title = (TextView) findViewById(R.id.xm_12_tv_title);
		if (intent.getExtras() != null) {
			mProjects = (Projects)intent.getExtras().getSerializable("my_projects");
			xm_12_tv_title.setText(mProjects.getProject_name());
		}

		findViewById(R.id.xm_12_RelativeLayout_back).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View v) {
						if(isFoujue){
							Intent intent=new Intent();
							setResult(foujue, intent);
						}
						finish();
					}
				});

		xm_project_add_RelativeLayout =(RelativeLayout)findViewById(R.id.xm_project_add_RelativeLayout);
		TextView xm_project_lxr = (TextView)xm_project_add_RelativeLayout.findViewById(R.id.xm_project_lxr);
		TextView xm_project_wcsq = (TextView)xm_project_add_RelativeLayout.findViewById(R.id.xm_project_wcsq);
		TextView xm_project_addzl = (TextView)xm_project_add_RelativeLayout.findViewById(R.id.xm_project_addzl);
		TextView xm_project_sp = (TextView)xm_project_add_RelativeLayout.findViewById(R.id.xm_project_sp);
		TextView xm_project_addbj = (TextView)xm_project_add_RelativeLayout.findViewById(R.id.xm_project_addbj);
		//加号按钮
		xm_project_add_RelativeLayout.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(xm_project_add_RelativeLayout.getVisibility() == View.VISIBLE){
					xm_project_add_RelativeLayout.setVisibility(View.GONE);
				}
			}
		});
		xm_project_lxr.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//添加联系人
				Intent intent = new Intent(mContext, XMChildAddContactsActivity.class);
				Bundle bundle = new Bundle();
				bundle.putSerializable("my_projects", mProjects);
				intent.putExtras(bundle);
				startActivity(intent);
			}
		});
		xm_project_wcsq.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//添加外出申请  
				Intent intent = new Intent(mContext, XMChildAddEgressActivity.class);
				Bundle bundle = new Bundle();
				bundle.putSerializable("my_projects", mProjects);
				intent.putExtras(bundle);
				startActivity(intent);
			}
		});
		xm_project_addzl.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//添加资料
				Intent intent = new Intent(mContext, XMChildAddDataActivity.class);
				Bundle bundle = new Bundle();
				bundle.putSerializable("my_projects", mProjects);
				intent.putExtras(bundle);
				startActivity(intent);
			}
		});
		xm_project_sp.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//审批信息
				Intent intent = new Intent(mContext, XMChildAddInfoActivity.class);
				Bundle bundle = new Bundle();
				bundle.putSerializable("my_projects", mProjects);
				intent.putExtras(bundle);
				startActivity(intent);
			}
		});
		xm_project_addbj.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//添加报价
				Intent intent = new Intent(mContext, XMChildAddBaoActivity.class);
				Bundle bundle = new Bundle();
				bundle.putSerializable("my_projects", mProjects);
				intent.putExtras(bundle);
				startActivity(intent);
			}
		});

		if(mProjects.isIs_edit_project() || mProjects.getIs_user_in_this_project() || mProjects.getIs_approve_project() || mProjects.getIs_final_approve() || mProjects.isIs_view_all_projects_or_reviewers()){
			findViewById(R.id.xm_12_RelativeLayout_add).setVisibility(View.VISIBLE);
		}
		
		findViewById(R.id.xm_12_RelativeLayout_add).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View v) {
						if(xm_project_add_RelativeLayout.getVisibility() == View.GONE){
							xm_project_add_RelativeLayout.setVisibility(View.VISIBLE);
						}else if(xm_project_add_RelativeLayout.getVisibility() == View.VISIBLE){
							xm_project_add_RelativeLayout.setVisibility(View.GONE);
						}
					}
				});
		
		findViewById(R.id.xm_12_RelativeLayout_add).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View v) {
						if(xm_project_add_RelativeLayout.getVisibility() == View.GONE){
							xm_project_add_RelativeLayout.setVisibility(View.VISIBLE);
						}else if(xm_project_add_RelativeLayout.getVisibility() == View.VISIBLE){
							xm_project_add_RelativeLayout.setVisibility(View.GONE);
						}
					}
				});
		
		if(mProjects.getIs_user_in_this_project()){
			findViewById(R.id.xm_project_addbj).setVisibility(View.VISIBLE);
		}
		 String title;
		 
		 TextView shenpiTv= (TextView) findViewById(R.id.shenping);
		if(mProjects.getIs_approved()){
			 title=mProjects.getApproved_by()+"于"+mProjects.getApproved_date()+"审批通过";
			 shenpiTv.setText(title);
			 if (mProjects.getIs_final_approve()) {
				 TextView fujue1=(TextView) findViewById(R.id.foujue);
				 ImageView shenpi_img1=(ImageView) findViewById(R.id.shenpi_img1);
				 String desctructiveTitle = "复审否决";
				 fujue1.setText(desctructiveTitle);
				 fujue1.setVisibility(View.VISIBLE);
				 shenpi_img1.setVisibility(View.VISIBLE);
		     }
		}else{
			title="正在组内审批";
			if(mProjects.getIs_final_approve() || (mProjects.getIs_approve_project() && !mProjects.getIs_creater())){
				TextView fujue1=(TextView) findViewById(R.id.foujue);
				ImageView shenpi_img2=(ImageView) findViewById(R.id.shenpi_img2);
				ImageView shenpi_img1=(ImageView) findViewById(R.id.shenpi_img1);
				TextView fujue2=(TextView) findViewById(R.id.foujue2);
				fujue1.setText("否决");
				fujue2.setText("通过");
				fujue2.setVisibility(View.VISIBLE);
				shenpi_img2.setVisibility(View.VISIBLE);
				fujue1.setVisibility(View.VISIBLE);
				shenpi_img1.setVisibility(View.VISIBLE);
			}
			shenpiTv.setText(title);
		}
		proInfoListData = new ArrayList<String>();
		if(!mProjects.isFlag_only_view_base_info()){
			proInfoListData.add("基本信息");
			proInfoListData.add("报价");
			proInfoListData.add("成员列表");
			proInfoListData.add("客户联系人");
			proInfoListData.add("外出申请/交流记录");
			proInfoListData.add("客户名片/资料");
			proInfoListData.add("审批信息");
			proInfoListData.add("审核操作");
			if(mProjects.getIs_user_in_this_project() || mProjects.isIs_edit_project()){
				proInfoListData.add("更改营销状态");
			}
		}else{
			findViewById(R.id.xm_12_RelativeLayout_add).setVisibility(View.GONE);
			proInfoListData.add("基本信息");
		}

		xm_12_lv = (ListView) findViewById(R.id.xm_12_lv);
		mXMChildAdapter = new XMChildAdapter(mContext, proInfoListData);
		xm_12_lv.setAdapter(mXMChildAdapter);
		xm_12_lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				Intent intent=null;
				Bundle bundle=null;
				// TODO Auto-generated method stub
				switch (arg2) {
				case 0:
					intent = new Intent(mContext, XMChildBasicInformationActivity.class);
					bundle = new Bundle();
					bundle.putSerializable("my_projects", mProjects);
					intent.putExtras(bundle);
					startActivity(intent);
					break;
				case 1:
					intent = new Intent(mContext, XMChildOfferActivity.class);
					bundle = new Bundle();
					bundle.putSerializable("my_projects", mProjects);
					intent.putExtras(bundle);
					startActivity(intent);
					break;
				case 2:
					intent = new Intent(mContext, XMChildMemberListActivity.class);
					bundle = new Bundle();
					bundle.putSerializable("my_projects", mProjects);
					bundle.putSerializable("baojia", "");
					intent.putExtras(bundle);
					startActivity(intent);
					break;
				case 3:
					intent = new Intent(mContext, XMChildCustomerContactActivity.class);
					bundle = new Bundle();
					bundle.putSerializable("my_projects", mProjects);
					intent.putExtras(bundle);
					startActivity(intent);
					break;
				case 4:
					intent = new Intent(mContext, XMChildApplyRecordActivity.class);
					bundle = new Bundle();
					bundle.putSerializable("my_projects", mProjects);
					intent.putExtras(bundle);
					startActivity(intent);
					break;
				case 5:
					intent = new Intent(mContext, XMChildDocumentationActivity.class);
					bundle = new Bundle();
					bundle.putSerializable("my_projects", mProjects);
					intent.putExtras(bundle);
					startActivity(intent);
					break;
				case 6:
					intent = new Intent(mContext, XMChildApprovalInformationActivity.class);
					bundle = new Bundle();
					bundle.putSerializable("my_projects", mProjects);
					intent.putExtras(bundle);
					startActivity(intent);
					break;
				case 7:
					final RelativeLayout xm_project_sh_RelativeLayout =(RelativeLayout)findViewById(R.id.xm_project_sh_RelativeLayout);
					TextView shenping = (TextView) xm_project_sh_RelativeLayout.findViewById(R.id.shenping); 
					TextView foujue = (TextView) xm_project_sh_RelativeLayout.findViewById(R.id.foujue); 
					TextView foujue2 = (TextView) xm_project_sh_RelativeLayout.findViewById(R.id.foujue2);
					TextView quxiao = (TextView) xm_project_sh_RelativeLayout.findViewById(R.id.quxiao); 

					xm_project_sh_RelativeLayout.setVisibility(View.VISIBLE);
					xm_project_sh_RelativeLayout.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
						}
					});
					shenping.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
						}
					});
					foujue.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							xm_project_sh_RelativeLayout.setVisibility(View.GONE);
							if(mProjects!=null){
								if(mProjects.getIs_approved()){
									getFouData("final");
								}else{
									getFouData("n");
								}
								
							}
						}
					});
					
					
					
					foujue2.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							xm_project_sh_RelativeLayout.setVisibility(View.GONE);
							if(mProjects!=null){
								getFouData("y");
							}
						}
					});
					
					quxiao.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							xm_project_sh_RelativeLayout.setVisibility(View.GONE);
						}
					});
					break;
				case 8:
					final RelativeLayout xm_edit_marking_RelativeLayout =(RelativeLayout)findViewById(R.id.xm_edit_marking_RelativeLayout);
					final ListView listView1 = (ListView)xm_edit_marking_RelativeLayout.findViewById(R.id.listView1);
					String[] mins = getResources().getStringArray( R.array.editmarking);
					index = Integer.parseInt(mProjects.getProcess_status())-1;
					listView1.setAdapter(new XMEditMarkingAdapter(mContext,mins,index));
					xm_edit_marking_RelativeLayout.setVisibility(View.VISIBLE);
					TextView xm_edit_marking_quxiao = (TextView) xm_edit_marking_RelativeLayout.findViewById(R.id.xm_edit_marking_quxiao);
					TextView xm_edit_marking_select = (TextView) xm_edit_marking_RelativeLayout.findViewById(R.id.xm_edit_marking_select);
					xm_edit_marking_quxiao.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							xm_edit_marking_RelativeLayout.setVisibility(View.GONE);
						}
					});
					xm_edit_marking_select.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							xm_edit_marking_RelativeLayout.setVisibility(View.GONE);
							getChangeYX(index+1);
						}
					});
					xm_edit_marking_RelativeLayout.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
						}
					});
					break;
				}
			}


		});
	}

	private void openDailog(String title, final String content) {
		new AlertDialog.Builder(mContext).setTitle(title)
		.setMessage(content).setPositiveButton("确定", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				if("登陆失效，需重新登陆".equals(content) || "join(f.username.errors)".equals(content)){
					LoginUtil.executeLoginFaild(mContext);
				}else{
					setResult(foujue);
					finish();
				}
			}
		}).show();
	}
	
	private void openDailog2(String title, String content) {
		new AlertDialog.Builder(mContext).setTitle(title)
		.setMessage(content).setPositiveButton("确定",null).show();
	}
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if(xm_project_add_RelativeLayout.getVisibility() == View.VISIBLE){
			xm_project_add_RelativeLayout.setVisibility(View.GONE);
		}
	}

	private void getFouData(String pad) {//1,2
		Network mNetword = new Network(mContext);
		if (!mNetword.isNetworkConnected()) {
			openDailog("网络提示", "网络未连接,请连接网络！");
		} else {
			final ProgressDialog progressDialog=ProgressDialogUtil.show(mContext);
			HashMap<String, String> mMap = new HashMap<String, String>();
			mMap.put("project_id", mProjects.getProject_id());
			mMap.put("action", pad+"");
			mMap.put("user_id", user_id);
			mMap.put("token", token);
			mMap.put("validation", CRMUserBaseInfo.kValication);
			String URL = Network.API_DOMAIN+"/project/approve?";

			RequestQueue requestQueue = Volley.newRequestQueue(mContext);
			JsonObjectPostRequest jsonObjectPostRequest = new JsonObjectPostRequest(
					URL, new Response.Listener<JSONObject>() {

						@Override
						public void onResponse(JSONObject response) {
							ProgressDialogUtil.dissmis(progressDialog);
							try {
								System.out.println("shenppppp  response="+response);  
								if (!response.isNull("errors")) {
									String errors = response.get("errors").toString();
									if (errors.equals("[]")) {
										openDailog("网络提示", "操作成功");
									} else {
										org.json.JSONArray jsonArr;
										if (!response.isNull("errors")) {
											LoginError mLoginError = new LoginError();
											jsonArr = response.getJSONArray("errors");
											if (jsonArr.length() > 0) {
												for (int i = 0; i < jsonArr.length(); i++) {
													JSONObject jsonObj2 = jsonArr.getJSONObject(i);
													if (!jsonObj2.isNull("desc")) {
														String desc = jsonObj2.getString("desc");
														openDailog("失败提示", desc);
														mLoginError.setDesc(desc);
													}
													if (!jsonObj2.isNull("value")) {
														String value = jsonObj2.getString("value");
														mLoginError.setValue(value);
													}
												}
											}
										}
									}
								}
							} catch (JSONException e) {
								e.printStackTrace();
							}
						}
					}, new Response.ErrorListener() {

						@Override
						public void onErrorResponse(VolleyError error) {
							ProgressDialogUtil.dissmis(progressDialog);
							Toast.makeText(mContext, "网络未连接！",
									Toast.LENGTH_LONG).show();
						}
					}, mMap);
			requestQueue.add(jsonObjectPostRequest);
			
		}
	}
	/**
	 * 
	 * @param index
	 */
	private void getChangeYX(final int index) {//1,2
		Network mNetword = new Network(mContext);
		if (!mNetword.isNetworkConnected()) {
			openDailog("网络提示", "网络未连接,请连接网络！");
		} else {
			final ProgressDialog progressDialog=ProgressDialogUtil.show(mContext);
			//http://crmsoap.woniuwo.cn/project/process?
			//project_id=53513934d5ac704cd3ac2ae1
			//&process_status=3
			//&user_id=bf4b484317a34e0cb63ed8e61320bae5
			//&token=770cde02b6ff4bcb8258cb5d17033ab3
			//&validation=gAJ9cQAoVQZsb2NhbGVxAVUFemhfQ05xAl
				
			HashMap<String, String> mMap = new HashMap<String, String>();
			mMap.put("project_id", mProjects.getProject_id());
			mMap.put("process_status", index+"");
			mMap.put("user_id", user_id);
			mMap.put("token", token);
			mMap.put("validation", CRMUserBaseInfo.kValication);
			String URL = Network.API_DOMAIN+"/project/process?";

			RequestQueue requestQueue = Volley.newRequestQueue(mContext);
			JsonObjectPostRequest jsonObjectPostRequest = new JsonObjectPostRequest(
					URL, new Response.Listener<JSONObject>() {

						@Override
						public void onResponse(JSONObject response) {
							ProgressDialogUtil.dissmis(progressDialog);
							try {
								System.out.println("shenppppp  response="+response);  
								if (!response.isNull("errors")) {
									String errors = response.get("errors").toString();
									if (errors.equals("[]")) {
										openDailog2("网络提示", "操作成功");
										mProjects.setProcess_status(index+"");
									} else {
										org.json.JSONArray jsonArr;
										if (!response.isNull("errors")) {
											LoginError mLoginError = new LoginError();
											jsonArr = response.getJSONArray("errors");
											if (jsonArr.length() > 0) {
												for (int i = 0; i < jsonArr.length(); i++) {
													JSONObject jsonObj2 = jsonArr.getJSONObject(i);
													if (!jsonObj2.isNull("desc")) {
														String desc = jsonObj2.getString("desc");
														openDailog("失败提示", desc);
														mLoginError.setDesc(desc);
													}
													if (!jsonObj2.isNull("value")) {
														String value = jsonObj2.getString("value");
														mLoginError.setValue(value);
													}
												}
											}
										}
									}
								}
							} catch (JSONException e) {
								e.printStackTrace();
							}
						}
					}, new Response.ErrorListener() {

						@Override
						public void onErrorResponse(VolleyError error) {
							ProgressDialogUtil.dissmis(progressDialog);
							Toast.makeText(mContext, "网络未连接！",
									Toast.LENGTH_LONG).show();
						}
					}, mMap);
			requestQueue.add(jsonObjectPostRequest);
		}
	}


}

class XMChildAdapter extends BaseAdapter {
	private ArrayList<String> DrugstoreDataList = null;
	private LayoutInflater listContainer; // 视图容器

	public final class ListItemView { // 自定义控件集合
		public TextView xm_12_item_tv;
	}

	public XMChildAdapter(Context mContext, ArrayList<String> data) {
		this.DrugstoreDataList = data;
		listContainer = (LayoutInflater) mContext
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}

	@Override
	public int getCount() {
		if (DrugstoreDataList != null) {
			return DrugstoreDataList.size();
		}
		return 0;
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return DrugstoreDataList.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		ListItemView listItemView = null;
		if (convertView == null) {
			listItemView = new ListItemView();
			// 获取list_item布局文件的视图
			convertView = listContainer.inflate(R.layout.xm_12_item, null);
			// 获取控件对象
			listItemView.xm_12_item_tv = (TextView) convertView.findViewById(R.id.xm_12_item_tv);
			// 设置控件集到convertView
			convertView.setTag(listItemView);
		} else {
			listItemView = (ListItemView) convertView.getTag();
		}
		// 设置文字和图片
		listItemView.xm_12_item_tv.setText((String) DrugstoreDataList
				.get(position));
		// listItemView.RelativeLayout_drugstorelist.setOnClickListener(new
		// OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// // TODO Auto-generated method stub
		// mContext.startActivity(new Intent(mContext,
		// DrugStoreDetailsActivity.class));
		// }
		// });
		return convertView;
	}

}